package org.chnxi.study.concurrent.deadlock;

import java.util.concurrent.TimeUnit;

/**
 * 使用synchronized模拟
 */
public class Demo01 {

    public static void main(String[] args) {
        MyProcessor processor = new MyProcessor();
        new Thread(processor , "Thread-1").start();
        new Thread(processor , "Thread-2").start();

        Object res1 = new Object();  //模拟资源1
        Object res2 = new Object();  //模拟资源2

    }

    static class MyProcessor implements Runnable{

        private Object res1 = new Object();  //模拟资源1
        private Object res2 = new Object();  //模拟资源2

        private boolean busiState = true;  //模拟业务分支

        @Override
        public void run() {

            // busiState == true，对res1加锁访问 -> 对res2加锁访问
            if(busiState){
                busiState = false;
                synchronized (res1){
                    System.out.println(Thread.currentThread().getName()+"->对res1锁定成功");
                    try {
                        TimeUnit.MILLISECONDS.sleep(100l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (res2){
                        System.out.println(Thread.currentThread().getName()+"->对res2锁定成功");
                    }
                }
            }
            // busiState == false，对res2加锁访问 -> 对res1加锁访问
            else{
                busiState = true;
                synchronized (res2){
                    System.out.println(Thread.currentThread().getName()+"->对res2锁定成功");
                    try {
                        TimeUnit.MILLISECONDS.sleep(100l);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (res1){
                        System.out.println(Thread.currentThread().getName()+"->对res1锁定成功");
                    }
                }
            }

        }
    }

}
